package com.wisezone.studentmanager.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.wisezone.studentmanager.server.UserServer;
import com.wisezone.studentmanager.server.impl.UserServerImpl;
import com.wisezone.studentmanager.utils.Pager;
import com.wisezone.studentmanager.utils.WebContext;

@WebServlet({ "/UserListServlet", "/user_list.servlet" })
public class UserListServlet extends HttpServlet {
	private UserServer userServer;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		WebApplicationContext webContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
		userServer = (UserServer)webContext.getBean("userServer");
		
		String currentPage = request.getParameter("page"); //获取当前页号
		String sexs = request.getParameter("sex");
		String ages = request.getParameter("age");
		String username = request.getParameter("username");
		
		int currentNo = currentPage == null ? 1 : Integer.parseInt(currentPage);
		int sex = sexs == null? -1 : Integer.parseInt(sexs);
		int age = (ages == null || "".equals(ages)) ? 0 : Integer.parseInt(ages);
		
		Pager pager = new Pager(userServer.getTotalCount(sex,username,age),currentNo);
		pager.setUrl(request.getContextPath()+"/user_list.servlet");
		pager.addParameter("sex", ""+sex);
		pager.addParameter("username", ""+username);
		pager.addParameter("age", ""+age);
		
		// 根据页号获取列表数据
		request.setAttribute("userLists", userServer.getUserLists(sex,username,age,pager.getIStart(), pager.getIStep()));
		request.setAttribute("currentPage", currentNo);
		request.setAttribute("pageCount", pager.getPageCount());
		request.setAttribute("pageStr", pager.getPageStr());
		WebContext.foward("user/user_list", request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
